<template>
  <auth-page>
    <view class="commodity" :style="{ '--themeColor': themeColor }">
      <view class="left" @click="handleShowImg(good.cover)" v-if="good.cover">
        <xhImg :src="good.cover" />
      </view>
      <view class="right" @click="showSku()">
        <view class="commodity-title">
          {{ good.title }}
        </view>
        <view class="bottom">
          <view class="price">
            <view class="logo">¥</view>
            <view class="content">
              {{ this.$myTool.toFixedNum(good.minPrice / 100) }}
            </view>
            <view class="qi">{{ good.hasMultiplePrice ? "起" : "" }}</view>
          </view>
          <view class="btns">
            <view
              class="select-btn"
              @click="handleMixinAuth(showSku)"
              v-if="good.skuInfo.specList.length > 0 && aloneNum <= 0"
            >
              选规格
            </view>
            <view class="prev-next" v-else>
              <view
                class="btn iconfont icon-jian"
                v-if="aloneNum > 0"
                @click.stop="handleMixinAuth(changeAloneNum)"
              ></view>
              <view class="text" v-if="aloneNum > 0">
                {{ aloneNum }}
              </view>
              <view
                class="btn iconfont icon-jia"
                @click.stop="handleMixinAuth(changeAloneNum, 1)"
              ></view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <root-portal>
      <u-popup
        :show="show"
        @close="closePop"
        :round="8"
        :zIndex="10078"
        @touchmove.stop.prevent
      >
        <view class="goods-pop" :style="{ '--themeColor': themeColor }">
          <view class="good-top">
            <view
              class="img"
              v-if="skuMsg.imgUrl"
              @click="handleShowImg(skuMsg.imgUrl)"
            >
              <xhImg :src="skuMsg.imgUrl" />
              <view
                class="no-commodity"
                v-if="skuMsg.stockNum == 0 || skuMsg.status == 0"
              >
                {{ skuMsg.stockNum == 0 ? "已售罄" : "已下架" }}
              </view>
            </view>
            <view class="top-right">
              <view class="price-left">
                <view class="price">
                  <span>¥</span>{{ skuMsg.price | formatCurrency }}
                </view>
                <view class="inve">库存{{ skuMsg.stockNum }}件</view>
              </view>
              <view class="good-clos">
                <u-icon
                  name="close"
                  @click="closePop"
                  color="#888888"
                  size="20"
                />
              </view>
            </view>
          </view>

          <scroll-view scroll-y class="scroll-content">
            <view class="desc" v-if="good.description">
              {{ good.description }}
            </view>
            <view class="sku" v-if="good.skuInfo.specList.length > 0">
              <view
                class="one"
                v-for="(item, index) in good.skuInfo.specList"
                :key="index"
              >
                <view class="title">{{ item.title }}</view>
                <view class="list">
                  <view
                    :class="[
                      'single',
                      skuActiveArr[index] == i.id ? 'active' : '',
                    ]"
                    v-for="(i, k) in item.attrList"
                    :key="k"
                    @click="selectArr(index, i.id)"
                  >
                    {{ i.title }}
                  </view>
                </view>
              </view>
            </view>
          </scroll-view>
          <view class="num">
            <view class="num-left">购买数量</view>
            <view class="num-right">
              <view
                :class="[
                  'btn iconfont icon-jian',
                  skuMsg.stockNum == 0 || skuMsg.status == 0
                    ? 'disable-click '
                    : '',
                ]"
                @click="changeNum()"
              ></view>
              <view class="text" v-if="queryParams.num > 0">
                {{ queryParams.num }}
              </view>
              <view
                :class="[
                  'btn iconfont icon-jia',
                  skuMsg.stockNum == 0 || skuMsg.status == 0
                    ? 'disable-click '
                    : '',
                ]"
                @click="changeNum(1)"
              ></view>
            </view>
          </view>
          <view class="goods-bottom">
            <view
              :class="[
                'btn',
                skuMsg.stockNum == 0 || skuMsg.status == 0
                  ? 'disable-click '
                  : '',
              ]"
              @click="handleMixinAuth(addCart)"
            >
              加入购物车
            </view>
            <view
              :class="[
                'btn',
                skuMsg.stockNum == 0 || skuMsg.status == 0 || shopStatus != 0
                  ? 'disable-click '
                  : '',
              ]"
              @click="handleMixinAuth(settLement)"
            >
              {{ shopStatus == 0 ? "去结算" : "门店已打烊" }}
            </view>
          </view>
        </view>
      </u-popup>
    </root-portal>

    <dineWayPop :visible.sync="showDine" @exportDinner="settLement" />
  </auth-page>
</template>

<script>
import { mapState } from "vuex";
import dineWayPop from "../dineWayPop";
import { saveCartItem } from "@/service/api/sp-store/commodity.js";
import { mixinAuth } from "@/mixin/sp-common/mixin-auth";

export default {
  mixins: [mixinAuth],

  components: {
    dineWayPop,
  },
  props: {
    good: {
      require: true,
      default: () => ({
        skuInfo: { specList: [], skuList: [] },
      }),
    },
  },

  data() {
    return {
      showDine: false,
      show: false,
      skuActiveArr: [],
      skuInfo: [],
      queryParams: {
        goodsId: "",
        num: 1,
        skuId: "",
        pubShopId: "",
        operation: 2,
      },
      skuMsg: {
        imgUrl: "",
        stockNum: 0,
        price: 0,
      },
      aloneNum: 0,
    };
  },
  mounted() {
    let {
      pubShopId,
      good: { goodId },
    } = this;
    this.queryParams = Object.assign({}, this.queryParams, {
      pubShopId,
      goodsId: goodId,
    });
    this.initSku();
    this.calculateAloneNum();
  },
  computed: {
    ...mapState("sp-store/index", [
      "pubShopId",
      "cartData",
      "shopStatus",
      "dineParams",
      "distributionType",
    ]),
    ...mapState("sp-common/base", ["themeColor"]),
  },
  watch: {
    cartData(newVal) {
      this.calculateAloneNum();
    },
    pubShopId(val) {
      this.queryParams.pubShopId = val;
    },
    good: {
      handler(value) {
        let {
          pubShopId,
          good: { goodId },
        } = this;
        this.queryParams = Object.assign({}, this.queryParams, {
          pubShopId,
          goodsId: goodId,
        });
        this.initSku();
      },
      deep: true,
    },
  },
  methods: {
    // sku商品加减购操作
    changeNum(type) {
      let {
        queryParams: { num },
        skuMsg: { stockNum },
      } = this;

      if (type) {
        if (num >= stockNum) {
          uni.showToast({ title: "库存不足", icon: "none" });
          return;
        }
        num++;
      } else {
        if (num == 1) {
          uni.showToast({ title: "商品数量不能少于1件", icon: "none" });
          return;
        }
        num--;
      }
      this.queryParams.num = num;
    },
    // 打开sku
    showSku() {
      // 设置sku默认项
      this.initSku();
      if (!wx.canIUse("root-portal")) {
        this.$store.commit("sp-store/index/SET_LOW_COMPATIBILITY", false);
      }
      this.show = true;
      // 检查门店状态
      this.$store.dispatch("sp-store/index/initShop");
    },
    closePop() {
      this.$store.commit("sp-store/index/SET_LOW_COMPATIBILITY", true);
      this.queryParams.num = 1;
      this.skuActiveArr = [];
      this.show = false;
    },
    // 初始化sku信息
    initSku() {
      let skuDefault = [];
      let {
        skuInfo: { specList, skuList },
      } = this.good;
      const skuList2 = uni.$u.deepClone(this.good).skuInfo.skuList;
      // 循环得出sku长度
      if (skuList && skuList.length > 0) {
        for (let index = 0; index < skuList[0].specAttrs.length; index++) {
          skuDefault.push(0);
        }
      }
      // 默认选择
      if (specList && specList.length > 0) {
        specList.forEach((element, index) => {
          skuDefault[index] = element.attrList[0].id;
        });
      }
      // 默认设置有库存的
      if (skuList && skuList.length > 0) {
        skuList.forEach((item, index) => {
          if (
            item.specAttrs.toString() == skuDefault.toString() &&
            item.stockNum > 0 &&
            item.status != 0
          ) {
            this.skuActiveArr = skuDefault;
          } else {
            this.skuActiveArr = skuList2.find(
              (ele) => ele.stockNum > 0 && ele.status != 0
            ).specAttrs;
          }
        });
      }
      this.setSkuMsg();
    },
    // 点击筛选操作
    selectArr(index, id) {
      this.skuActiveArr[index] = id;
      this.setSkuMsg();
    },
    // 设置sku相关信息
    setSkuMsg() {
      let {
        good: {
          // skuInfo: { skuList },
          cover,
        },
        skuActiveArr,
      } = this;
      const skuList = uni.$u.deepClone(this.good).skuInfo.skuList;
      if (skuList && skuList.length > 0) {
        // 匹配sku中相同的
        skuList.forEach((item) => {
          if (item.specAttrs.toString() == skuActiveArr.toString()) {
            let { skuId, stockNum, price, imgUrl, status } = item;
            this.queryParams.skuId = skuId;
            imgUrl = imgUrl ? imgUrl : cover;
            this.skuMsg = {
              imgUrl,
              stockNum,
              price,
              status,
            };
          }
        });
      }
    },
    handleShowImg(value) {
      if (!value) return;
      let imgUrl = process.env.VUE_APP_BASE_FileUrl + value;
      uni.previewImage({
        current: "",
        urls: [imgUrl],
      });
    },
    // 添加到购物车
    async addCart() {
      let { queryParams } = this;
      queryParams.operation = 2;
      this.$store.dispatch("sp-store/index/initShop");
      let res = await saveCartItem(queryParams);
      if (res != -1) {
        if (res == null) {
          await this.$store.dispatch("sp-store/index/initCart");
          await uni.showToast({ title: "添加购物车成功", icon: "none" });
          this.closePop();
        } else {
          await uni.showToast({ title: res, icon: "none" });
        }
      }
    },
    // 商品在购物车数量的计算
    calculateAloneNum() {
      let {
        good: { goodId },
        cartData: { items },
      } = this;
      let aloneNum = 0;
      if (items) {
        items.forEach((item) => {
          if (item.goodsId === goodId) {
            aloneNum += item.num;
          }
        });
      }
      this.aloneNum = aloneNum;
    },
    // 单规格商品加减购操作
    changeAloneNum(type) {
      let {
        queryParams,
        queryParams: { goodsId },
        skuMsg: { stockNum },
        good: {
          skuInfo: { specList },
        },
        aloneNum,
        cartData: { items },
      } = this;
      queryParams.operation = 1;
      let middleNum = aloneNum;
      if (specList.length <= 0) {
        if (type) {
          if (middleNum >= stockNum) {
            uni.showToast({ title: "库存不足", icon: "none" });
            return;
          }
          middleNum++;
        } else {
          middleNum--;
        }
        let aloneParams = Object.assign({}, queryParams);
        aloneParams.num = middleNum;
        saveCartItem(aloneParams).then((res) => {
          if (res == null) {
            this.aloneNum = middleNum;
            this.$store.dispatch("sp-store/index/initCart");
          } else {
            uni.showToast({ title: res, icon: "none" });
          }
        });
      } else {
        let i = 0;
        items.forEach((ele) => {
          ele.goodsId == goodsId ? i++ : "";
        });
        if (type) {
          this.showSku();
        } else {
          if (i > 1) {
            uni.showToast({
              title: "请前往购物车进行商品的增减",
              icon: "none",
            });
          } else {
            if (type) {
              if (middleNum >= stockNum) {
                uni.showToast({ title: "库存不足", icon: "none" });
                return;
              }
              middleNum++;
            } else {
              middleNum--;
            }
            let aloneParams = Object.assign({}, queryParams);
            aloneParams.num = middleNum;
            saveCartItem(aloneParams).then((res) => {
              if (res == null) {
                this.aloneNum = middleNum;
                this.$store.dispatch("sp-store/index/initCart");
              } else {
                uni.showToast({ title: res, icon: "none" });
              }
            });
          }
        }
      }
    },
    // 单商品结算
    async settLement() {
      // this.show = false
      let shopSta = await this.$myTool.verifyShop();
      let {
        queryParams: { skuId, num },
        good: {
          skuInfo: { skuList, storeId, specList },
          goodId,
          cover,
          title,
        },
        dineParams,
        distributionType: { datas },
      } = this;
      let skuData = skuList.find((item) => item.skuId == skuId);
      let specAttrs = skuData.specAttrs;
      let specLists = [];
      if (specList.length > 0) {
        specList.forEach((item, index) => {
          item.attrList.forEach((dItem) => {
            if (dItem.id == specAttrs[index]) {
              specLists.push(dItem.title);
            }
          });
        });
      }
      if (!dineParams) {
        if (datas && datas.length < 2) {
          this.$store.commit("sp-store/index/SET_DINE", datas[0]);
        } else {
          this.showDine = true;
          return;
        }
      }
      skuData.cover = cover;
      let queryParams = {
        storeId,
        source: 1,
        items: [
          {
            goodsId: goodId,
            num,
            ...skuData,
            title,
            skuInfo: JSON.stringify(specLists),
          },
        ],
      };
      if (shopSta) {
        // this.$myTool.jumpPage("storeOrderSubmit", {
        //   // order: JSON.stringify(queryParams),
        //   order: encodeURIComponent(JSON.stringify(queryParams)),
        // });

        uni.navigateTo({
          url: `pages/sp-order/pages/store-order-submit/index`,
          success: (res) => {
            res.eventChannel.emit("order", { data: queryParams });
          },
        });

        this.closePop();
      } else {
        this.$store.dispatch("sp-store/index/initShop");
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.commodity {
  margin-top: 30rpx;
  display: flex;
  .left {
    width: 150rpx;
    height: 150rpx;
    border-radius: 8rpx;
    overflow: hidden;
    position: relative;
  }
  .right {
    flex: 1;
    padding: 0rpx 25rpx 10rpx 20rpx;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .commodity-title {
      font-size: 29rpx;
      font-weight: bold;
      color: #131313;
    }
    .bottom {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .price {
        font-size: 36rpx;
        font-family: PingFang SC;
        font-weight: 500;
        color: #f05357;
        display: flex;
        align-items: baseline;
        .logo {
          font-size: 29rpx;
          font-weight: normal;
        }
        .content {
          margin: 0 5rpx 0 3rpx;
        }
        .qi {
          font-size: 27rpx;
          font-weight: normal;
        }
      }
      .btns {
        display: flex;
        .select-btn {
          width: 125rpx;
          height: 44rpx;
          background: var(--theme-color);
          border-radius: 22rpx;
          font-size: 28rpx;
          font-weight: 500;
          color: #ffffff;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        .prev-next {
          display: flex;
          align-items: center;
          .btn {
            width: 44rpx;
            height: 44rpx;
            border: 1px solid var(--theme-color);
            border-radius: 50%;
            background: var(--theme-color);
            display: flex;
            justify-content: center;
            align-items: center;
            color: #fff;
          }
          .icon-jian {
            background-color: #ffffff;
            color: #525252;
          }
          .no-change {
          }
          .text {
            margin: 0 30rpx;
            font-size: 28rpx;
            font-weight: bold;
            color: #131313;
          }
        }
      }
    }
  }
}
.goods-pop {
  padding: 40rpx 40rpx 20rpx 30rpx;
  max-height: 66vh;
  .good-top {
    display: flex;
    margin-bottom: 30rpx;
    .img {
      width: 170rpx;
      height: 170rpx;
      border-radius: 15rpx;
      position: relative;
      .no-commodity {
        background: #13131350;
        padding: 8rpx 0;
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 26rpx;
        font-weight: 500;
        color: #ffffff;
      }
    }
    .top-right {
      flex: 1;
      display: flex;
      justify-content: space-between;
      margin-left: 20rpx;
      .price-left {
        .price {
          font-weight: bold;
          color: #f05357;
          font-size: 45rpx;
          span {
            font-size: 36rpx;
          }
        }
      }
    }
  }
  .desc {
    font-size: 28rpx;
    font-weight: 500;
    color: #888888;
    line-height: 40rpx;
    margin-bottom: 65rpx;
    overflow: hidden; /* 溢出隐藏 */
    display: -webkit-box; /* 设置为弹性盒子 */
    -webkit-box-orient: vertical; /* 设置为垂直方向 */
    -webkit-line-clamp: 2; /* 显示行数 */
    text-overflow: ellipsis; /* 使用省略号显示 */
  }
  .scroll-content{
    min-height: 1vh;
    max-height: 35vh;
    overflow-y: scroll;
  }
  .sku {
  
    .one {
      margin-bottom: 50rpx;
      font-size: 29rpx;
      font-weight: bold;
      color: #131313;
      .list {
        display: flex;
        flex-wrap: wrap;
        margin-top: 30rpx;
        .single {
          // min-height: 60rpx;
          background: #f5f5f5;
          border-radius: 30rpx;
          padding: 10rpx 30rpx;
          display: flex;
          justify-content: center;
          align-items: center;
          margin-right: 25rpx;
          margin-bottom: 15rpx;
          border: 1px solid #f5f5f5 !important;
        }
        .active {
          border-color: var(--theme-color) !important;
          color: var(--theme-color) !important;
          background-color: #fff;
        }
      }
    }
  }
  .num {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 29rpx;
    font-weight: bold;
    color: #131313;
    margin-bottom: 60rpx;
    .num-right {
      display: flex;
      align-items: center;
      .btn {
        width: 44rpx;
        height: 44rpx;
        border: 1px solid var(--theme-color);
        border-radius: 50%;
        background: var(--theme-color);
        display: flex;
        justify-content: center;
        align-items: center;
        color: #fff;
      }
      .icon-jian {
        background-color: #ffffff;
        color: #525252;
      }
      .no-change {
      }
      .text {
        margin: 0 30rpx;
        font-size: 28rpx;
        font-weight: bold;
        color: #131313;
      }
    }
  }
  .goods-bottom {
    width: calc(100% - 80rpx);
    margin: 0 auto;
    display: flex;
    justify-content: space-between;
    > view:nth-child(1) {
      color: var(--theme-color);
    }
    > view:last-child {
      background-color: var(--theme-color);
      color: #fff;
    }
    .btn {
      width: calc(100% / 2 - 40rpx);
      height: 80rpx;
      border: 2px solid var(--theme-color);
      border-radius: 40rpx;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}
</style>